package mqttClient

//MQTT 向中心注册
import (
	"encoding/json"
	"errors"
	"github.com/parnurzeal/gorequest"
	"gitee.com/yuyuaa/easyGoTool.git/gofunc"
	"gitee.com/yuyuaa/wensGoMqtt.git/common"
	"log"
	"strconv"
	"strings"
	"time"
)

//mqtt设备类型与后台字典对应
type MqttDevType int

const (
	MqttDevType_WlwControl MqttDevType = 0 //养殖场环境控制器
	MqttDevType_liaota     MqttDevType = 1 //料塔
	MqttDevType_jianjieji  MqttDevType = 2 //益康生降解机
)

//获取注册二维码url
func (self *Client) GetRegQrcodeUrl() (error, string) {
	host := common.Const_regist_host                //http://w.wens.com.cn
	registEndPoint := common.Const_api_phone_regist // /mqtt/registpage
	devId := self.DevId                             //设备唯一id
	url := host + registEndPoint + "?deviceId=" + devId + "&typeValue=" + strconv.Itoa(int(self.DevType))
	log.Println(url)
	return nil, url
}

//检查deviceId=xxx的设备是否已经注册了，注册了就按照规则转换为clientId，用户名，密码。没注册返回err
func (self *Client) CheckHasRegist() error {
	host := common.Const_regist_host
	checkEndPoint := common.Const_api_dev_check
	deviceId := self.DevId
	str := gofunc.StrFunc{}
	tokenstr := str.Md5(deviceId + "wens.com.cn")
	//http://wt.wens.com.cn//mqtt/checkdeviceid?deviceId=xxx
	url := host + checkEndPoint + "?deviceId=" + deviceId + "&token=" + tokenstr
	log.Println("请求或者mqtt登录信息:", url)
	_, bodyBytes, errs := gorequest.New().Timeout(15 * time.Second).
		Get(url).
		EndBytes()
	if len(bodyBytes) == 0 { //超时的时候什么都不会返回
		return errors.New("请求超时")
	}
	if errs != nil {
		return errs[0]
	}
	//返回的结构形式
	type res struct {
		Msg  string `json:"msg"`
		Code int    `json:"code"`
		Data struct {
			Password string `json:"password"`
			ClientId string `json:"clientid"`
			Username string `json:"username"`
		} `json:"data"`
	}
	re := res{}
	err := json.Unmarshal(bodyBytes, &re)
	if err != nil {
		return errors.New("格式解析不成功")
	}
	log.Println(re)
	if re.Data.ClientId == "" { //没有注册好的devid返回{"msg":"成功","code":1,"data":null}
		return errors.New("该设备id还没注册好")
	} else { //请求成功了
		self.parseUidToLoginInfo(re.Data.ClientId, re.Data.Username, re.Data.Password)
	}
	return nil
}

//通过Uid获取连接用信息
func (self *Client) GetConnectInfoByUid() (clientId, userName, passWord string) {

	//根据uid是否为空判断是否注册了
	if self.Config.Mqtt.ClientId == "" {
		clientId = "未注册"
		userName = "未注册"
		passWord = "未注册"
		return
	}

	clientId = self.Config.Mqtt.ClientId
	userName = self.Config.Mqtt.UserName
	passWord = self.Config.Mqtt.PassWord
	return
}

//向mqtt服务器发送节点信息
func (self *Client) SendNodeInfo(node []string) error {
	if len(node) == 0 { //如果存入的为空
		return errors.New("没有任何节点信息")
	}
	host := common.Const_regist_host
	checkEndPoint := common.Const_api_send_node_info
	deviceId := self.DevId
	str := gofunc.StrFunc{}
	tokenstr := str.Md5(deviceId + "wens.com.cn")
	nodestr := strings.Join(node, "!!")
	//http://wznyz.wens.com.cn/znyz/a/appreg/mqtt/regNode?deviceId=1&token=bea3c6a76196cf50fc3dda0f6bacc5d0&nodes=sss|
	// sssssss
	url := host + checkEndPoint + "?deviceId=" + deviceId + "&token=" + tokenstr + "&nodes=" + nodestr
	log.Println("请求添加mqtt节点信息:", url)
	_, bodyBytes, errs := gorequest.New().Timeout(2 * time.Second).
		Get(url).
		EndBytes()
	if len(bodyBytes) == 0 { //超时的时候什么都不会返回
		return errors.New("请求超时")
	}
	if errs != nil {
		return errs[0]
	}
	return nil
}
